package com.atguigu.spzx.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.spzx.common.constant.CacheConstant;
import com.atguigu.spzx.model.vo.common.Result;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * order值相同，按照默认顺序执行：
 *          全局过滤器 -> 默认过滤器 -> 路由过滤器
 *
 *  AuthGlobalFilter作用：
 *      如果路径中带/auth，必须登录状态，才会放行，否则，拒绝访问。
 *      如果路径中没有带/auth，那么，直接放行，无需要登录即可访问。
 */
@Component
@Slf4j
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Autowired
    RedisTemplate<String,String> redisTemplate;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String uri  = exchange.getRequest().getURI().toString();
        String path  = exchange.getRequest().getURI().getPath();
        log.info("uri="+uri);
        log.info("path="+path);
        if(antPathMatcher.match("/api/**/auth/**",path)){ // true表示，路径中是携带/auth，必须登录
            List<String> tokenList = exchange.getRequest().getHeaders().get("token");
            String token = null;
            if(!CollectionUtils.isEmpty(tokenList)){
                token = tokenList.get(0);
            }
            if(!StringUtils.hasText(token)){
                return out(exchange.getResponse(),ResultCodeEnum.LOGIN_AUTH); //拒绝访问
            }

            String userInfoJson =  redisTemplate.opsForValue().get(CacheConstant.LOGIN_USERINFO_PREFIX+token);
            if(!StringUtils.hasText(userInfoJson)){
                return out(exchange.getResponse(),ResultCodeEnum.LOGIN_AUTH); //拒绝访问
            }
        }

        return chain.filter(exchange); // 路径中不携带/auth，直接放行，无需登录。
    }


    private Mono<Void> out(ServerHttpResponse response, ResultCodeEnum resultCodeEnum) {
        Result result = Result.build(null, resultCodeEnum);
        byte[] bits = JSONObject.toJSONString(result).getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
